package main

import (
	"flag"
	"fmt"
	"os"
	"path/filepath"
	"strings"
)

func getDirectorySize(dirPath string) (int64, error) {
	var totalSize int64

	err := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.IsDir() {
			totalSize += info.Size()
		}
		return nil
	})

	if err != nil {
		return 0, err
	}

	return totalSize, nil
}

func main() {

	flag.Parse()
	var dir string
	var command string
	var err error
	if flag.NArg() == 0 {
		// 当前工作目录
		dir, err = os.Getwd()
		if err != nil {
			panic(err)
		}
	} else {
		dir = flag.Arg(0)
		command = flag.Arg(1)
	}

	// fmt.Println(dir)
	entries, err := os.ReadDir(dir)
	if err != nil {
		panic(err)
	}

	// 打印每个条目的名字
	for _, entry := range entries {
		info, _ := entry.Info()
		mode := info.Mode()
		// fmt.Printf("info: %v\n", info)
		// 根据模式判断是文件还是目录
		if mode.IsDir() {
			if strings.HasPrefix(command, "--") {
				if "--size" == command {
					size, err := getDirectorySize("")
					if err != nil {
						panic(err)
					} else {
						fmt.Printf("dir: %s size: %d \n", entry.Name(), size)
					}
				}
			} else {
				fmt.Printf("dir: %s\n", entry.Name())
			}
		} else if mode.IsRegular() {
			size := info.Size()
			if size > 1024*1024 {
				size = size / (1024 * 1024)
				fmt.Printf("file: %s , size = %d mb\n", entry.Name(), size)
			} else {
				size = size / 1024
				fmt.Printf("file: %s , size = %d kb\n", entry.Name(), size)
			}

		} else {
			fmt.Printf("other: %s\n", entry.Name())
		}
	}
}
